import 'dart:convert' as convert;
import 'package:http/http.dart' as http;

void main() async {
  add(x, y) {
    return x + y;
  }

  await someFuture();
  print(add(20, 30));
  print(add(20.0, 30.0));
  print(add("20", "30"));
  print(addExt(1, 2));

  try {
    final post = await fetchPost();
    print(post.title);
    print(post.userId);
  } catch (e) {
    print("获取数据失败: $e");
    // 可以提供默认数据
    final defaultPost = PostResponse("默认标题", 0);
    print(defaultPost.title);
    print(defaultPost.userId);
  }
}

dynamic addExt(dynamic x, dynamic y) {
  return x + y;
}

Future<void> someFuture() async {
  print("other threads");
}

Future<PostResponse> fetchPost() async {
  var url = Uri.https('jsonplaceholder.typicode.com', '/posts/1');
  final res = await http.get(
    url,
    headers: {
      // 必须，否则遇到错误
      'User-Agent': 'Dart/3.0', // 添加用户代理头
      'Accept': 'application/json',
    },
  );

  if (res.statusCode == 200) {
    Map<String, dynamic> data = convert.jsonDecode(res.body);
    return PostResponse(data["title"], data["userId"]);
  } else {
    throw Exception("处理响应失败: ${res.statusCode}");
  }
}

class PostResponse {
  String? title;
  int? userId;

  PostResponse(this.title, this.userId);
}
